package com.lanzuo.yxd.scanner.scanner;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.lanzuo.yxd.scanner.api.MesInterface;
import com.lanzuo.yxd.scanner.config.SpringContextHolder;
import com.lanzuo.yxd.scanner.constant.OneCommandConstant;
import com.lanzuo.yxd.scanner.dto.SubmitResult;
import com.lanzuo.yxd.scanner.scanner.event.MessageReceiveEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Component
public class ScannerWaitNotifyCoordinator {

    /**
     * key: ip : position
     */
    private final Map<String, ScanResultHolder> holders = new ConcurrentHashMap<>();

    @Resource
    MesInterface mesInterface;

    public ScanResultHolder createHolder(Integer lane, String ip, String position) {
        String key = lane + "-" + ip + ":" + position;
        ScanResultHolder holder = new ScanResultHolder();
        holders.put(key, holder);
        return holder;
    }

    /**
     * 使用 @Async 实现异步处理（避免阻塞采集线程）
     */
    @Async
    @EventListener
    public void onReceivedMessage(MessageReceiveEvent event) {
        // 处理事件
        log.info("接收到扫码枪事件消息， message:\n{} ", JSONUtil.toJsonPrettyStr(event));

        List<String> panelSns = event.getPanelSns();
        String workStationCode = SpringContextHolder.getProperty("one.eap.work_station_code", "");
        String request = StrUtil.format(OneCommandConstant.ONE_PANEL_RELATION_INFO, CollUtil.join(panelSns, ","), workStationCode);
        try {
            // mes 校验
            JSONObject response = mesInterface.submitReport(new JSONObject(request));
            log.info("Get message from mes: \n {}", JSONUtil.toJsonPrettyStr(response));

            if (response.containsKey("code")) {
                int resCode = response.getInt("code");
                if (resCode != 1) {
                    log.error("[MES]上报拼板编号异常, panels:{}, Code:{}， Message:{}", panelSns, resCode, response.get("msg"));
                    complete(event, false, resCode, response.getStr("msg"));
                } else {
                    complete(event, true, resCode, response.getStr("msg"));
                }
            } else {
                complete(event, false, 0, "Mes结果异常");
            }
        } catch (Exception e) {
            log.error("远程调用mes接口异常", e);
        }
    }

    /**
     * 请求结束
     *
     * @param event
     * @param result
     */
    private void complete(MessageReceiveEvent event, Boolean result, Integer code, String msg) {
        // cache key
        String key = event.getLane() + "-" + event.getScannerIp() + ":" + event.getScannerPosition();
        ScanResultHolder holder = holders.remove(key);
        if (holder != null) {
            holder.complete(new SubmitResult(result, code, msg));
        }
    }

}